#include "user.h"
#include "ui_user.h"
#include "mainwindow.h"

user::user(QString userID,QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::user)
{
    ui->setupUi(this);
    setConfig();

    this->userID = userID;
    flag = false;

    db =new dataBase();
    QString userMessage = db->query_userMessage(userID);
    QStringList userdata = userMessage.split(",",Qt::SkipEmptyParts);

    userName = userdata[1];
    QString phoneNumber = userdata[2];

    ui->label->setText("用户ID:"+userID);
    ui->label_2->setText("联系方式:"+phoneNumber);
    ui->label_3->setText("用户名:"+userName);

    client = new chatClient(userName,caCertificateFilePath,clientCertificateFilePath,clientKeyPath);
    connect(client,&chatClient::receiveMessage,this,&user::receiveMessage);

}

user::user(QString fileName,QString userID,QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::user)
{
    ui->setupUi(this);
    setConfig(fileName);

    this->userID = userID;
    flag = false;

    db =new dataBase();
    QString userMessage = db->query_userMessage(userID);
    QStringList userdata = userMessage.split(",",Qt::SkipEmptyParts);

    userName = userdata[1];
    QString phoneNumber = userdata[2];

    ui->label->setText("用户ID:"+userID);
    ui->label_2->setText("联系方式:"+phoneNumber);
    ui->label_3->setText("用户名:"+userName);

    client = new chatClient(userName,caCertificateFilePath,clientCertificateFilePath,clientKeyPath);
    connect(client,&chatClient::receiveMessage,this,&user::receiveMessage);
}

void user::setConfig(QString fileName){
    QFile file(fileName);

    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){
        qDebug()<<"无法打开配置文件";
        return;
    }
    QTextStream in(&file);
    int flag = 1;
    while(!in.atEnd()){
        QString line = in.readLine();

        if(line.trimmed().isEmpty()){
            continue;
        }else{
            if(flag == 1){
                this->caCertificateFilePath = line;
                flag++;
            }else if(flag == 2){
                this->clientCertificateFilePath = line;
                flag++;
            }else if(flag ==3){
                this->clientKeyPath = line;
                flag++;
            }else{
                break;
            }
        }
    }
}

void user::setConfig(){
    QFile file("E:/Qt_workspace/untitled7/config.txt");

    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){
        qDebug()<<"无法打开配置文件";
        return;
    }
    QTextStream in(&file);
    int flag = 1;
    while(!in.atEnd()){
        QString line = in.readLine();

        if(line.trimmed().isEmpty()){
            continue;
        }else{
            if(flag == 1){
                this->caCertificateFilePath = line;
                flag++;
            }else if(flag == 2){
                this->clientCertificateFilePath = line;
                flag++;
            }else if(flag ==3){
                this->clientKeyPath = line;
                flag++;
            }else{
                break;
            }
        }
    }
}

void user::receiveMessage(QString message){
    QRegularExpression regex(R"(command\s+(\S+):\s*(.*))");
    QRegularExpressionMatch match = regex.match(message);
    if (match.hasMatch()) {
        QString command = match.captured(1).trimmed(); // 指令
        QString commandContent = match.captured(2).trimmed(); // 提取消息内容
        if(command == "-query"){
            QStringList userList = commandContent.split(" ",Qt::SkipEmptyParts);
            // 获取当前的本地时间
            QDateTime currentTime = QDateTime::currentDateTime();
            // 格式化时间，使用 [yyyy/MM/dd hh:mm:ss] 格式
            QString formattedTime = "[" + currentTime.toString("yyyy/MM/dd hh:mm:ss") + "]";
            ui->textBrowser_2->clear();
            ui->textBrowser_2->append(formattedTime + "在线:");
            foreach (QString user, userList) {
                ui->textBrowser_2->append(user);
            }
        }

    }else{
        ui->textBrowser->append(message);
    }

}

user::~user()
{
    delete db;
    if(!flag){
        delete client;
    }
    delete ui;
}

void user::on_sendButton_clicked()
{

    QString message = ui->message->text();

    QString new_message;
    // 获取当前的本地时间
    QDateTime currentTime = QDateTime::currentDateTime();
    // 格式化时间，使用 [yyyy/MM/dd hh:mm:ss] 格式
    QString formattedTime = "[" + currentTime.toString("yyyy/MM/dd hh:mm:ss") + "]";

    QRegularExpression regex(R"(To\s+(\w+):\s*(.*))");
    QRegularExpressionMatch match = regex.match(message);

    if (match.hasMatch()) {
        QString recipient = match.captured(1).trimmed(); // 提取收件人
        ui->label_4->setText("接收者:"+recipient);
        QString messageContent = match.captured(2).trimmed(); // 提取消息内容
        new_message = "To "+recipient+": "+formattedTime+" "+userName+": "+messageContent;

        db->add_chatMessage(formattedTime,userID,recipient,messageContent);
    }else{
        new_message = formattedTime+" "+userName+": "+message;
        db->add_chatMessage(formattedTime,userID,"所有人",message);
        ui->label_4->setText("接收者: 所有人");
    }
    client->sendMessage(new_message);
    ui->message->clear();
}


void user::on_pushButton_clicked()
{
    ui->textBrowser->clear();
}


void user::on_pushButton_2_clicked()
{
    modifyUserMessage *m = new modifyUserMessage(userID);
    m->show();
}


void user::on_query_clicked()
{
    client->sendMessage("command -query");
}

void user::on_index_clicked()
{
    MainWindow *w = new MainWindow();
    w->show();
    delete client;
    flag = true;
    this->close();
}

